<template>
  <el-form :model="userModel">
    <el-form-item>
      <div class="cover-box">

        <!--
          auto-upload:设置是否自动上传,设置为true
          action:设置服务器接口路径(有跨域问题，所以也要加上/api)
          name:设置上传的文件字段名(对应于后端的名称file)
          headers:设置上传的请求头
          on-success:设置上传成功的回调函数
         -->

        <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                   action="/api/upload"
                   name="file"
                   :on-success="uploadSuccess"
        >
          <img v-if="userModel.headImg" :src="userModel.headImg" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </div>
    </el-form-item>
  </el-form>


</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';

const userModel = ref({
  id:'',
  username:'',
  password:'',
  headImg:'',
  phone:'',
})

//文件上传成功回调函数
function uploadSuccess(res){
  userModel.value.headImg = res.data;
}
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 278px;
  height: 278px;
  border: 1px dashed #d9d9d9;
  cursor: pointer;
}
.cover-box .avatar-uploader-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 将加号按钮居中定位 */
  font-size: 36px; /* 设置加号按钮大小 */
  color: #999; /* 设置颜色 */
}
</style>